<!--
 * @Author: lixb
 * @Date: 2020-08-24 09:39:18
 * @LastEditTime: 2020-09-26 15:51:13
 * @Descripttion: 查看员工信息
-->
<template>
  <div>
    <el-drawer
      title="贺卡祝福"
      :visible.sync="isOpen"
      :direction="direction"
      size="680px"
      style="height: 100vh;"
      :wrapper-closable="false"
      :before-close="beforeClose"
    >
      <div class="greet-card">
        <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px">
          <el-form-item label="节日场景：" prop="festivalScene">
            <div class="festivalType">
              <div
                v-for="(item, index) in festivalList"
                :key="index"
                :class="{ active: item.isShow }"
                @click="switchFestival(index, item)"
              >
                {{ item.name }}
                <img v-show="item.isShow" src="@/assets/img/radioImg.png" />
              </div>
            </div>
          </el-form-item>
          <el-form-item id="images" label="选择贺卡：" prop="cardId">
            <div
              v-for="item in zhongqiuImgList"
              v-show="festivalName == '中秋节'"
              :key="item.id"
              class="card-list"
            >
              <img
                :src="item.url"
                :class="{ active: item.isShow }"
                @click="selectGreetCard(zhongqiuImgList, item)"
              />
            </div>
            <div
              v-for="item in guoqingImgList"
              v-show="festivalName == '国庆节'"
              :key="item.id"
              class="card-list"
            >
              <img
                :src="item.url"
                :class="{ active: item.isShow }"
                @click="selectGreetCard(guoqingImgList, item)"
              />
            </div>
            <div
              v-for="item in shengdanImgList"
              v-show="festivalName == '圣诞节'"
              :key="item.id"
              class="card-list"
            >
              <img
                :src="item.url"
                :class="{ active: item.isShow }"
                @click="selectGreetCard(shengdanImgList, item)"
              />
            </div>
          </el-form-item>
          <el-form-item label="贺卡封面：" prop="imagePath">
            <el-upload
              action="customUpload"
              list-type="picture-card"
              :class="{ hideUpload: hideUpload }"
              :limit="limit"
              :disabled="loading"
              :on-error="uploadError"
              :before-upload="beforeAvatarUpload"
              :file-list="fileList"
              :on-remove="handleRemove"
            >
              <i v-loading="loading" class="el-icon-plus"></i>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png/bmp文件，且不超过5MB</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="展示时间：" prop="showTime">
            <el-date-picker
              v-model="ruleForm.showTime"
              type="datetimerange"
              range-separator="至"
              value-format="yyyy-MM-dd HH:mm:ss"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="发送对象：" prop="selectCard">
            全体员工
          </el-form-item>
          <el-form-item label="祝福词：" prop="content">
            <el-input
              v-model="ruleForm.content"
              type="textarea"
              placeholder="请输入内容"
              maxlength="140"
              show-word-limit
            ></el-input>
          </el-form-item>
          <el-form-item>
            <div style="float:right;">
              <el-button @click="resetForm('ruleForm')">重置</el-button>
              <!-- <el-button :disabled="previewUrl == ''" @click="previewImg()">预览效果</el-button> -->
              <el-button type="primary" @click="submitForm('ruleForm')">确认发送</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
    <previewImg
      :preview-url="previewUrl"
      :is-show="isShow"
      @closePreview="closePreview"
    ></previewImg>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex';
  const guoqing1 = require('@/assets/img/greetCard/guoqing-1.png');
  const guoqing2 = require('@/assets/img/greetCard/guoqing-2.png');
  const guoqing3 = require('@/assets/img/greetCard/guoqing-3.png');
  const zhongqiu1 = require('@/assets/img/greetCard/zhongqiu-1.png');
  const zhongqiu2 = require('@/assets/img/greetCard/zhongqiu-2.png');
  const zhongqiu3 = require('@/assets/img/greetCard/zhongqiu-3.png');
  const shengdan1 = require('@/assets/img/greetCard/shengdan-1.png');
  const shengdan2 = require('@/assets/img/greetCard/shengdan-2.png');
  const shengdan3 = require('@/assets/img/greetCard/shengdan-3.png');
  import previewImg from '@/components/previewImg/index.vue';
  import { sendGreetCard } from '@/api/greetCard';
  import { uploadImg } from '@/api/upload';
  // import { isImg } from '@/utils/regExpUtil';
  export default {
    components: { previewImg },
    props: {
      isOpen: {
        type: Boolean,
        required: true,
      },
    },
    data() {
      return {
        hideUpload: false,
        loading: false,
        limit: 1,
        isShow: false,
        previewUrl: '',
        festivalName: '中秋节',
        direction: 'rtl',
        festivalList: [
          { name: '中秋节', isShow: true },
          { name: '国庆节', isShow: false },
          { name: '圣诞节', isShow: false },
        ],
        zhongqiuImgList: [
          { url: zhongqiu1, id: 1, isShow: false },
          { url: zhongqiu2, id: 2, isShow: false },
          { url: zhongqiu3, id: 3, isShow: false },
        ],
        shengdanImgList: [
          { url: shengdan1, id: 4, isShow: false },
          { url: shengdan2, id: 5, isShow: false },
          { url: shengdan3, id: 6, isShow: false },
        ],
        guoqingImgList: [
          { url: guoqing1, id: 7, isShow: false },
          { url: guoqing2, id: 8, isShow: false },
          { url: guoqing3, id: 9, isShow: false },
        ],
        ruleForm: {
          showTime: '',
          content: '',
          imagePath: '',
          cardId: '',
        },
        rules: {
          content: [{ required: true, message: '请填写祝福语', trigger: 'blur' }],
          showTime: [{ required: true, message: '请选择展示时间', trigger: 'change' }],
          cardId: [{ required: true, message: '请选择节日模板', trigger: 'change' }],
          imagePath: [{ required: true, message: '请上传贺卡封面', trigger: 'change' }],
        },
        fileList: [],
      };
    },
    computed: {
      ...mapGetters('user', ['userInfo']),
      isClient() {
        return !!this.userInfo.isClient || false;
      },
    },
    watch: {},
    activated() {},
    methods: {
      //选择节日
      switchFestival(index, item) {
        this.festivalList.map(function(currentValue) {
          //移除节日按钮的选中效果
          currentValue.isShow = false;
        });
        this.clearSelectImage(); //移除卡片的选中效果
        this.ruleForm.cardId = ''; //清空卡片id，因为当前切换了节日
        this.festivalList[index]['isShow'] = true; //当前点击的按钮高亮
        this.festivalName = item.name; //记录当前选中的节日名称
      },
      //选择卡片
      selectGreetCard(list, item) {
        this.clearSelectImage(); //移除其他卡片的选中效果
        this.ruleForm.cardId = item.id; //记录卡片id
        this.previewUrl = item.url; //记录图片预览路径
        item.isShow = true; //当前卡片高亮
      },
      //清空所有卡片选中效果；
      clearSelectImage() {
        this.zhongqiuImgList.map(function(currentValue) {
          currentValue.isShow = false;
        });
        this.guoqingImgList.map(function(currentValue) {
          currentValue.isShow = false;
        });
        this.shengdanImgList.map(function(currentValue) {
          currentValue.isShow = false;
        });
      },
      //表单提交
      submitForm(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            let params = {
              content: this.ruleForm.content,
              cardType: this.ruleForm.cardId,
              festival: this.festivalName,
              sendDate: this.ruleForm.showTime[0],
              endDate: this.ruleForm.showTime[1],
              smallPicPath: this.ruleForm.imagePath,
              sendObject: 1,
            };
            sendGreetCard(params).then(res => {
              if (res.status == 200) {
                this.$message.success('提交成功！');
                this.$emit('closeDrawer');
              }
            });
          }
        });
      },
      //预览图片
      previewImg() {
        this.isShow = true;
      },
      //重置
      resetForm(formName) {
        this.$refs[formName].resetFields();
        this.clearSelectImage();
        this.previewUrl = '';
        this.ruleForm.imagePath = '';
        this.hideUpload = false;
        this.fileList = [];
      },
      //关闭图片预览弹出层
      closePreview() {
        this.isShow = false;
      },
      //文件上传之前
      beforeAvatarUpload(file) {
        this.fileList = [];
        const isLt5M = file.size / 1024 / 1024 < 5;
        const isImg = /^.*\.(png|jpg|jpeg|bmp)$/i.test(file.name);
        if (!isImg) {
          this.$message.error('上传图片只能是 JPG/PNG/BMP 格式!');
        }
        if (!isLt5M) {
          this.$message.error('上传图片大小不能超过 5MB!');
        }
        if (isImg && isLt5M) {
          this.loading = true;
          this.onUpload(file);
        }
        return false;
      },
      //文件上传成功
      uploadSuccess(response) {
        this.ruleForm.imagePath = response.data.filePath;
        this.hideUpload = true;
        this.loading = false;
      },
      //文件上传失败
      uploadError() {
        this.loading = false;
      },
      //文件删除
      handleRemove() {
        this.ruleForm.imagePath = '';
        this.hideUpload = false;
        this.fileList = [];
      },
      //关闭弹窗
      beforeClose() {
        this.$emit('closeDrawer', false);
        this.resetForm('ruleForm');
      },
      async onUpload(file) {
        let _flie = file;
        if (this.isClient) {
          const { electronReadFile } = require('@/utils/electronUpload');
          _flie = await electronReadFile(_flie.path);
        }
        const formData = new FormData(); //创建form对象
        formData.append('file', _flie);
        const res = await uploadImg(formData);
        const { data = null } = res;
        if (data) {
          this.fileList.push({
            name: file.name,
            url: data.filePath || '',
          });
        }
        this.uploadSuccess(res);
      },
    },
  };
</script>
<style>
  .greet-card .hideUpload .el-upload--picture-card {
    display: none;
  }
</style>
<style lang="scss" scoped>
  /deep/ .el-drawer__body {
    padding: 20px;
    overflow: auto;
  }
  .active {
    border: 2px solid #3770eb !important;
  }
  .festivalType {
    div {
      position: relative;
      width: 80px;
      height: 36px;
      display: inline-block;
      text-align: center;
      margin-left: 15px;
      border: 2px solid #f4f0f3;
      line-height: 34px;
      border-radius: 7px;
      cursor: pointer;
      img {
        position: absolute;
        right: -1px;
        bottom: -1px;
      }
    }
  }
  .card-list {
    display: inline-block;
    margin-right: 20px;
    cursor: pointer;
    img {
      width: 150px;
      height: 100%;
    }
  }
</style>
